package cn.xclink.wechat.service;


import java.util.Date;


import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cn.xclink.common.mapper.BaseMapper;
import cn.xclink.common.service.BaseService;
import cn.xclink.wechat.entity.Token;
import cn.xclink.wechat.mapper.TokenMapper;
/**
 * 获取本地access_token,超时就自动刷新,但是本地无法检测token是否失效
 * @author ljp
 *
 */
@Service
public class TokenService extends BaseService<Token> {
	@Autowired
	private TokenMapper mapper;
	@Autowired
	WxTokenService wxTokenService;
	
	public List<Token> find(Token record) {
		return mapper.select(record);
	}


	@Override
	public BaseMapper<Token> getMapper() {
		// TODO Auto-generated method stub
		return mapper;
	}


//  获取本地accesstoken
	 public String LocalAccessToken(){
		 Date date = new Date();
		 Token t = get(1L);
		 if(t!=null){
			 
			 if(t.getAccessToken()!=null&&!t.getAccessToken().equals("")){
				 Date updateTime =t.getLastUpdateTime();
				 Long time = date.getTime()-updateTime.getTime();
				 //如果时间差超过7000*1000毫秒，那么重新获取微信服务器的accesstoken并存到数据库中
				 if (time > 7000000) {
					 String access_token =wxTokenService.getAccessToken();
//	            	 存在数据库中并返回
					 Token entity = new Token();
					 entity.setAccessToken(access_token);
					 entity.setTokenId(1L);
					 entity.setLastUpdateTime(date);
					 mapper.updateByPrimaryKeySelective(entity);
					 return access_token;
				 } else {
					 return t.getAccessToken();
				 }
			 }else{
//			不存在accesstoken，从微信服务器中获取
				 String access_token =wxTokenService.getAccessToken();
//			 存在数据库中并返回
				 Token entity = new Token();
				 entity.setAccessToken(access_token);
				 entity.setTokenId(1L);
				 entity.setLastUpdateTime(date);
				 mapper.updateByPrimaryKeySelective(entity);
				 return access_token;
			 }
		 }else{
//			 没存时获取
			 String access_token =wxTokenService.getAccessToken();
			 Token entity = new Token();
			 entity.setAccessToken(access_token);
			 entity.setTokenId(1L);
			 entity.setLastUpdateTime(date);
			 entity.setCreateTime(date);
			 mapper.insertSelective(entity);
			 return access_token;
		 }
		 
	  }






}
